<template>
	<view class="tea-manager-app" style="height: 100%;">
		<!--
		<view v-if="!isLogin" style="height: 100%;background-color: white;">
			<view class="login-button" style="margin-top:200upx;"  @click="goPage('/pages/user/auth/login')">
				请先登录
			</view>
		</view>
		-->
		<view class="search-top"></view>
		
		<view class="page-body">
			<!--
			<view class="tabs" style="display: flex;"  v-if="!isRent">
				<view class="tab-item" :class="{selected:(tabItem.value==tabItemValue)}" v-for="(tabItem,tabItemKey) in tabItems" @click="tabClick(tabItem)"
				 :key="tabItemKey">{{tabItem.label}}</view>
			</view>
			-->
		    <view class="page-section page-section-gap" v-if="!isRent" style="height: 100%;">
				<!--
		        <map v-if="showMap" @tap="onMapTap" style="width: 100%; height: 100%;" :latitude="map.latitude" :longitude="map.longitude" id="teaMap" ref="teaMap" :markers="map.covers" @markertap="markertap">
		        </map>
				-->
				<view class="tea-list" v-if="!showMap" >
					<view class="search-part" style="display: flex;padding-bottom:20upx;margin-top:20upx;">
						<view class="search-option" style="height:60upx;border-radius:10upx;flex:1">
							<image src="../../../static/search-icon.png" style="width:48upx;margin-left:20upx;" mode="aspectFit"/>
							<input @input="searchByName" class="keyword-input" v-model="searchOption.keyword" style="flex:1;" />
							<text style="margin-right:20upx;">搜索</text>
						</view>		
					</view>
					<view  style="padding-top:100upx;">
						<view class="tea-item" v-if="item.show" v-for="(item,key) in listData.items" :key="key" @click="goPage('/pages/tea/default/room?teaHouseId='+item.teaHouseId)">
							<view class="content">
								<view class="title">{{item.name}}</view>
								<view class="address">{{item.address}}</view>
							</view>
							<view class="map-item-info">
								<view class="image">
									<image v-if="!item.images" src="../../../static/store.png" mode="aspectFit" style="width: 200upx;height:100upx;"></image>
									<image v-if="item.images" :src="item.images" mode="aspectFit" style="width: 200upx;height:100upx;"></image>
								</view>
								<div class="map-info" @click.stop="showMapInfo(item)">地图位置</div>
							</view>
						</view>
					</view>
				</view>
		    </view>
			<view class="order-info" v-if="isRent">
				<view class="head">{{order.roomName}}</view>
				<view class="fields">
					<view class="field">
						<view class="title">订单编号:</view>
						<view class="value">{{order.orderNO}}</view>
					</view>
					<view class="field">
						<view class="title">开始时间：</view>
						<view class="value">
						{{order.startTime}}
						</view>
					</view>
					<view class="field">
						<view class="title">已租用：</view>
						<view class="value">
							<myTimer ref="myTimer"></myTimer>
						</view>
					</view>
					<view class="field">
						<view class="title">备注：</view>
						<view class="value">{{order.remark}}</view>
					</view>
					
					<view class="field">
						<view class="title">茶室大门：</view>
						<view class="value">
							<!--
							<image :src="'data:image/jpg;base64,' + order.qcCode" style="width:300upx;height:300upx;background-color: #ccc;"></image>
							-->
							<view class="btn btn-primary" @click="showQrcodeDialog('qrcodeDailog')">打开二维码</view>
						</view>
					</view>
					
					<view class="field">
						<view class="title">包厢门：</view>
						<view class="value">
							
							<view class="btn btn-primary" @click="showQrcodeDialog('qrcodeRoomDailog')">打开二维码</view>
							
							<!--
							<image :src="'data:image/jpg;base64,' + order.qcCodeRoom" style="width:300upx;height:300upx;background-color: #ccc;"></image>
							-->
							
							<!--
							<image v-if="qcCodeRoom" :src="'data:image/jpg;base64,' + qcCodeRoom" style="margin:0 auto;width:400upx;height:400upx;background-color: #ccc;"></image>
							<view class="qrcode-is-load" v-if="!qcCodeRoom">加载中..</view>
							-->
						</view>
					</view>
				</view>
				<view class="cancel-button" @click="cancelOrder">
					结束订单
				</view>
				<view class="tip-items">
					<view class="tip-item">
						<view class="tip-item-head">操作提示</view>
						<view class="tip-item-content">
							<view>1、请先用手指把锁面点亮；</view>
							<view>2、把上面二维码对准锁面上部摄像头，距离5-10厘米；</view>
							<view>3、当摄像头变成绿色，锁发出轻柔开门声即可。</view>
							<view>4、如有故障请联系：15010008980</view>
						</view>
					</view>
					<view class="tip-item">
						<view class="tip-item-head">提醒告知</view>
						<view class="tip-item-content">
							<view>本茶室为您提供喝茶交流场所，请勿在本场所做法律规定外的行为。</view>
							<view>本茶室不为违规违法行为承担连带责任</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<modal :show="qrcodeDailog.show"  @close="qrcodeDailog.show=false" @cancel="qrcodeDailog.show=false" :show-cancel="false" confirm-text="关闭" cancel-text="关闭">
			<view class="dialog-head">茶室大门</view>
			<view class="app-info-dialog" style="padding:20upx;display: flex;justify-content: center;align-items: center;">
				<image v-if="order.qcCode" :src="'data:image/jpg;base64,' + order.qcCode" style="margin:0 auto;width:400upx;height:400upx;background-color: #ccc;"></image>
				<view class="qrcode-is-load" v-if="!order.qcCode">加载中..</view>
			</view>
		</modal>
		
		<modal :show="qrcodeRoomDailog.show"  @close="qrcodeRoomDailog.show=false" @cancel="qrcodeRoomDailog.show=false" :show-cancel="false" confirm-text="关闭" cancel-text="关闭">
			<view class="dialog-head">包厢门</view>
			<view class="app-info-dialog" style="padding:20upx;display: flex;justify-content: center;align-items: center;">
				<image v-if="order.qcCodeRoom" :src="'data:image/jpg;base64,' + order.qcCodeRoom" style="margin:0 auto;width:400upx;height:400upx;background-color: #ccc;"></image>
				<view class="qrcode-is-load" v-if="!order.qcCodeRoom">加载中..</view>
			</view>
		</modal>
		
	</view>
</template>

<script>
	import wPicker from "@/components/w-picker/w-picker.vue"
	import util from '@/libs/util.js'
	import globalConfig from '../../../config'
	import Modal from '@/components/neil-modal/neil-modal.vue';
	import myTimer from '@/components/my-timer.vue';
			
	const baseHttp = globalConfig.API_HOST
	
	export default {
	    data() {
	        return {
				isLogin: false,
				showMap: false,
				isTimerStart: false,
				tabItemValue: 0,
				baseHttp: baseHttp,
				isCancelSubmit: false,
				user: {
					userId:null,
					teaHouseName: null
				},
				qrcodeDailog:{
					show: false
				},
				qrcodeRoomDailog: {
					show: false
				},
				tabItems: [
					{value: 0, label: '地图'},
					{value: 1, label: '列表'}
				],
				qcCodeRoom: '',
				order:{
					"orderNO":"",
					"orderType":0,
					"payState":0,
					"predictMoney":8000,
					"remark":"租用包厢",
					"rentMins":4,
					"roomId":9,
					"startTime":"2021-01-01 16:05:38",
					"teaHouseId":8,
					"userId":6,
					"qcCode":"",
					"qcCodeRoom":""
				},
				map: {
					latitude: '',
					longitude: '',
					covers: [
						/*
						{
							id: 1,
						    latitude: 23.02882,
						    longitude: 113.14278,
							title: '地点1',
							width:50,
							height:50,
						    iconPath: '../../../static/point.png'
						},{
							id: 2,
						    latitude: 23.05980,
						    longitude: 113.16039,
							title: '地点2',
							width:50,
							height:50,
						    iconPath: '../../../static/point.png'
						}*/
					]
				},
				isRent: false,
				listData: {
					items: [
					]
				},
				searchOption: {
					keyword: ''
				}
				/*
				isLogin: false,
				tabItemValue: 0,
				teaListDialog: {
					show: false
				},
				searchOption: {
					keyword: ''
				},
				addDialog: {
					show: false
				},
				currentTeaHouse: {
					id: '',
					name: ''
				},
				teaHouse: {
					items: []
				},
				listData: {
					items: [
						{name: '包厢管理',icon:'../../../static/room.png', 'link': '/pages/tea/room/list'},
						{name: '用户管理',icon:'../../../static/user_manager.png', 'link': '/pages/tea/user/list'},
						{name: '配置管理',icon:'../../../static/config.png', 'link': '/pages/tea/default/config'},
						{name: '设备管理',icon:'../../../static/machine.png', 'link': '/pages/tea/machine/list'},
						{name: '任务管理',icon:'../../../static/task.png', 'link': '/pages/tea/task/list'},
						{name: '用户余额日志',icon:'../../../static/money.png', 'link': '/pages/tea/useMoneyLog/list'},
						{name: '邀请管理',icon:'../../../static/invite.png', 'link': '/pages/tea/invite/list'}
					]
				}
				*/
	        }
	    },
		onLoad(params) {
			/*
			uni.getLocation({
			    type: 'gcj02',
			    success:  (res) => {
					this.map.longitude = res.longitude;
					this.map.latitude = res.latitude;
					this.$refs.teaMap.moveToLocation({
						longitude: res.longitude,
						latitude: res.latitude,
						success:(info) => {
							console.log(info)
						},
						fail:(info) => {
							console.log(info)
						},
						complete:(info) => {
							console.log(info)
						}
					});
			    }
			});
			*/
		},
		onReady() {

		},
		onShow() {
			
			uni.switchTab({
			    url: '/pages/tea/v2/map'
			})
			
			if (global.isLogin()) {
				this.isLogin = true
			} else {
				this.isLogin = false
			}
			this.getDataList();	
			if (this.isLogin) {
				
				/*
				uni.getLocation({
				    type: 'gcj02',
				    success:  (res) => {
						this.map.latitude = res.latitude
						this.map.longitude = res.longitude
						
						let appMap = uni.createMapContext("teaMap", this);
						appMap.moveToLocation({
							longitude: res.longitude,
							latitude: res.latitude
						});
						this.getMapTeaHouse(res.longitude,res.latitude);
				    }
				});
				*/
				

				/*
				appMap.getCenterLocation({    
				   success(res) {    
					   console.log(JSON.stringify(res))    
				   }    
				});
				*/
				//appMap.showUserLocation(true);
				
				this.getUserDetail();

				
				this.checkIsRent();
				setInterval(() => {
					this.checkIsRent();
				},60000);
				setInterval(() => {
					if (this.isRent) {
						this.getQRImage();
					}
				},300000);
				
				
			}
		},
		components: {
			Modal,
			myTimer
		},
		computed: {
			/*
			dateRangeValue() {
				return [this.homeData.startDate, this.homeData.endDate]
			}
			*/
		},
	    methods: {
			...util,
			getUserDetail() {
				
				this.$api.post('/user/getInfo', {
					
				}).then((response) => {
					if (response.ret === 1) {
						this.user = response.data;
						this.searchOption.keyword = this.user.teaHouseName;
						//this.searchByName({target:{value:this.user.teaHouseName}});
					} else {
						this.$Message.info(response.msg)
					}
				})

			},
			showMapInfo(item) {
				//console.log(item);
				//console.log(item);
				if (this.isLogin) {
					this.goPage("/pages/tea/default/mapDetail?id="+item.teaHouseId)
				}
				
				return false;
			},
			onMapTap(tapPosition) {
				//console.log(tapPosition);
				//tapPosition.detail.latitude
				this.map.covers = [];
				this.getMapTeaHouse(tapPosition.detail.longitude,tapPosition.detail.latitude);
			},
			showQrcodeDialog(field) {
				this[field].show = true;
				this.getQRImage();
			},
			getMapTeaHouse(lon,lat) {
				this.$api.post('/teaHouse/getNear',
					{
						lon:lon,
						lat:lat,
						radius:500000
					}
				).then((response) => {
					this.map.covers = [];
					if (response.data) {
						for(let i = 0; i < response.data.length;i++) {
							this.map.covers.push({
								id: response.data[i].teaHouseId,
							    latitude: response.data[i].lat,
							    longitude: response.data[i].lon,
								title: response.data[i].name,
								width:50,
								height:50,
							    iconPath: '../../../static/point.png'
							});
						}
						console.log(this.map.covers);
					}
					
					this.map.covers.push({
						id: -1,
					    latitude: lat,
					    longitude: lon,
						title: '我的位置',
						width:50,
						height:50,
					    iconPath: '../../../static/my_point.png'
					});
				});
			},
			markertap(event) {
				if (event.detail.markerId>1) {
					this.goPage('/pages/tea/default/room?teaHouseId='+event.detail.markerId)
				}
			},
			tabClick(item) {
				this.tabItemValue = item.value
				this.showMap = !this.showMap
			},
			searchByName(event) {
				let name = event.target.value;
				if (name && name.length > 0) {
					
					for(let i = 0; i < this.listData.items.length; i++) {
						//console.log(this.listData.items[i]);
						let index = this.listData.items[i].name.indexOf(name);
						if (index!=-1) {
							this.listData.items[i].show = true;
						} else {
							this.listData.items[i].show = false;
						}
					}
				} else {
					this.setField(this.listData.items, 'show', true);
				}
			},
			cancelOrder() {
				if (this.isCancelSubmit) {
					return false;
				}
				uni.showModal({
				    title: '提示',
				    content: '确定结束？',
				    success:  (res) => {
				        if (res.confirm) {

							//提交请求中
							uni.showLoading({
								title: '提交请求中'
							});
							
							this._cancelOrder();
							
				        } else if (res.cancel) {
				            //console.log('用户点击取消');
				        }
				    }
				});

			},
			_cancelOrder() {
				
				this.isCancelSubmit = true;
				
				this.$api.post('/roomOrder/finishOrder',
					{
					}
				).then((response) => {
					if (response.ret===1) {
						this.$Message.success("结束订单成功");
						this.checkIsRent();
						this.isCancelSubmit = false;
					} else {
						if (response.msg=="余额不足") {
							//this.$Message.error("what");
							//调用充值接口
							
							//判断是否会员
							if (response.data===null || response.data===undefined) {
								this.isCancelSubmit = false;
								this.$Message.error(response.msg);
								this.goPage("/pages/user/info/vip");
							} else {
								this.toPay(response.data);
							}
							
						} else {
							this.$Message.error(response.msg);
							this.isCancelSubmit = false;
						}
						
					}
					
				});
			},
			toPay(money) {
				wx.login({
					success: (res) => {
						if (res.code) {
							this.wxCode = res.code;
							
							this.$api.post('/weixin/recharge',
							  {
								code: this.wxCode,
								money: money
							  }
							).then((response) => {
							  if (response.ret===1) {
								//console.log(response);
								let json = "{"+response.data+"}";						
								json = json.replace(/'/g,'"');
								json = JSON.parse(json);
								
								uni.requestPayment({
									provider: 'wxpay',
									timeStamp: json.timeStamp,
									nonceStr: json.nonceStr,
									package: json.package,
									signType: json.signType,
									paySign: json.paySign,
									success:  (res) => {
										//this._cancelOrder();
										this.$Message.success("支付成功");
										/*
										uni.navigateBack({
											delta: 1
										});
										*/
									},
									fail: function (err) {
										console.log('fail:' + JSON.stringify(err));
									}
								});
															
							  } else {
								this.$Message.error(response.msg)
							  }
							  this.isCancelSubmit = false;
							});
						}
					}
				});
				
			},
			getOrderInfo() {
				//判断当前是否有使用中的订单
				
			},
			getQRImage() {
				
				this.$api.post('/roomOrder/getQRImage',
					{
						lockType: 0
					}
				).then((imageResponse) => {
					this.order.qcCode = imageResponse.data;
				});
				
				this.$api.post('/roomOrder/getQRImage',
					{
						lockType: 1
					}
				).then((imageResponse) => {
					this.$nextTick(() => {
						this.order.qcCodeRoom = imageResponse.data;
					})
					
					//console.log("what");
					//console.log(this.order.qcCodeRoom)
				});	
				
				
			},
			checkIsRent() {
			
				this.$api.post("/roomOrder/getRenting",
					{
						
					}
				).then((response) => {
					
					if (response.ret===1) {

						this.order = response.data;

						let startTime = new Date(this.order.startTime.replace(/-/g,'/')).getTime()/1000;
						//var endTime = new Date(this.selectedTime.replace(/-/g,'/')).getTime()/1000;
						let currentTime = Date.parse(new Date())/1000;
						let useTime = currentTime - startTime;
						
						this.order.useTime = "00:00:00";

						if (this.isRent==false) {
							this.getQRImage();
						}
						this.isRent = true;
						
						this.$nextTick(() => {
							this.$refs.myTimer.setCurrentTime(useTime);
							if (this.isTimerStart==false) {
								this.isTimerStart = true;
								this.$refs.myTimer.start();
							}
						})

					} else {
						this.isRent = false;
					}
				});
			},
			getDataList() {
				uni.showLoading({
					title: '加载中'
				});
				this.$api.post('/teaHouse/queryPage',
					{
						pageNo: 1
					}
				).then((response) => {
					response.data.items = this.setField(response.data, 'show', true);
					
					this.listData.items = response.data

					if (this.user.teaHouseName) {
						//this.searchByName({target:{value:this.user.teaHouseName}});
					}
					
					/*
					for(let i = 0; i < this.listData.items.length; i++) {
						//console.log(this.listData.items[i]);
						this.listData.items[i]['typeLabel'] = this.getLabelFromOptions(this.formSearchOptions.typeList, this.listData.items[i]['type']);
					}
					*/
					
					uni.hideLoading()
				});
			},
			goPage(url) {
				if (!this.isLogin) {
					uni.navigateTo({url: '/pages/user/auth/auth'})
				} else {
					//console.log(url);
					uni.navigateTo({url: url})
				}
				
			},
	    }
	}
</script>

<style lang="scss">
	page{
		height: 100%;
	}
	
	.tea-manager-app{
		background-color: #F5F4F8;
		height: 100%;
		color:#707070;
		.head{
			padding:20upx;
			background-color: white;
		}
		.tip-items{
			.tip-item{
				margin:20upx;
				.tip-item-head{
					font-weight: bold;
					font-size:40upx;
					text-align:center;
					border-bottom: 1upx solid #eee;
					margin-bottom: 10upx;
					padding-bottom: 10upx;
				}
				.tip-item-content{
					
				}
			}
		}
		.qrcode-is-load{
			font-size:24upx;
			width:400upx;
			height:400upx;
			background-color: #ccc;
			text-align: center;
			line-height: 400upx;
		}
		
		.tabs{
			border-right:none;
			margin-top:-1upx;
			border-radius: 5upx;
			width:100%;
			background-color: #3385FF;
			color:white;
			font-size:28upx;
			.tab-item{
				text-align: center;
				width:50%;
				padding: 20upx;
				/*border-right:1upx solid #1296db;*/
			}
			.selected{
				background-color: #3385FF;
				font-weight: bold;
				/*border-bottom: 3upx solid blue;*/
			}
		}
		
		
		.page-section,.page-body,.tea-manager-app{
			height: 100%;
		}
		.dialog-head{
			text-align: center;
			padding: 10upx;
			border-bottom: 1upx solid #eee;
		}
		.login-button{
			font-size:30upx;
			margin:0 auto;
			background-color:#3385FF;
			color:white;
			width:646upx;
			height:100upx;
			text-align: center;
			line-height: 100upx;
		}
		.search-part{
			position: fixed;
			/*top:0;*/
			width:100%;
			background-color: #F5F4F8;
			.search-option-input{
				.keyword-input{
					
				}
			}
			
			.search-option{
				background-color: white;
				margin:0 20upx;
				color:#BBBBBB;
				display: flex;
				/*justify-content: center;*/
				align-items: center;
			}
			.tabs{
				border:1px solid #108EE9;
				border-right:none;
				margin:0 20upx;
				border-radius: 5upx;
				width:calc(100% - 40upx);
				background-color: white;
				.tab-item{
					text-align: center;
					width:33%;
					padding: 8upx;
					color:#108EE9;
					border-right:1upx solid #108EE9;
				}
				.selected{
					background-color: #108EE9;
					color:white;
				
				}
			}
		}
		
		.order-info{
			background-color: white;
			padding-bottom:100upx;
			.head{
				border-bottom:1upx solid #eee;
				text-align: center;
				font-weight: bold;
			}
			.fields{
				
			}
			.field{
				padding: 10upx;
				display: flex;
				.title{
					width:250upx;
				}
				.value{
					
				}
			}
			.cancel-button{
				font-size:40upx;
				margin:0 auto;
				color:white;
				width:750upx;
				
				height:120upx;
				text-align: center;
				line-height: 120upx;
				margin-top:100upx;
				background-color:#D81E06;
				position: fixed;
				bottom:0;
			}
		}
		
		
		.tea-list{
			.tea-item{
				background-color: white;
				padding: 20upx;
				margin-bottom:20upx;
				display: flex;
				.image{
					
				}
				.map-item-info{
					display: flex;
					flex-direction: column;
					.map-info{
						text-align: center;
						font-size:24upx;
						/*margin:0 auto;*/
						background-color:#3385FF;
						color:white;
						
						height:45upx;
						text-align: center;
						line-height: 45upx;
					}
				}
				.content{
					flex: 1;
					.title{
						color:#3385FF;
						font-size:32upx;
					}
				}
			}
		}
		
		
		.content-items{
			display: flex;
			flex-wrap: wrap;
			margin-top:20upx;
			
			.content-item{
				font-size:28upx;
				color:#707070;
				width: 200upx;
				height:200upx;
				
				margin-right:20upx;
				margin-left:20upx;
				margin-bottom:20upx;
				border: 1upx solid #eee;
				background-color: white;
				justify-content: center;
				align-items: center;
				text-align: center;
			}
		}

	}
	
</style>
